<template>
  <view class="container">
    <!-- 数字时钟显示 -->
    <view class="clock-container">
      <view class="time-display">
        <text class="time">{{ currentTime }}</text>
      </view>
      <view class="date-display">
        <text class="date">{{ currentDate }}</text>
      </view>
    </view>

    <!-- 功能按钮 -->
    <view class="button-container">
      <button class="add-alarm-btn" @click="goToAddAlarm">
        <text class="btn-text">添加闹钟</text>
      </button>
      <button class="test-btn" @click="goToRealDeviceTest">
        <text class="btn-text">📱 真机震动测试</text>
      </button>
    </view>

    <!-- 最近闹钟预览 -->
    <view class="next-alarm-container" v-if="nextAlarm">
      <view class="next-alarm-header">
        <text class="next-alarm-label">⏰ 下一个闹钟</text>
      </view>
      <view class="next-alarm-info">
        <text class="next-alarm-time">{{ nextAlarm.time }}</text>
        <text class="next-alarm-name">{{ nextAlarm.label }}</text>
        <view class="alarm-features-preview">
          <text v-if="nextAlarm.vibrate" class="feature-preview">📳</text>
          <text v-if="nextAlarm.enableRingtone" class="feature-preview">🎵</text>
        </view>
      </view>
      <view class="countdown" v-if="countdown">
        <text class="countdown-text">{{ countdown }}</text>
      </view>
      <view class="next-alarm-type">
        <text class="type-text">{{ getAlarmTypeText(nextAlarm) }}</text>
      </view>
    </view>

    <!-- 无闹钟提示 -->
    <view class="no-alarm" v-else>
      <text class="no-alarm-text">暂无活跃闹钟</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentTime: "",
      currentDate: "",
      nextAlarm: null,
      countdown: "",
      timer: null,
      alarmTimer: null,
    };
  },
  onShow() {
    this.updateTime();
    this.timer = setInterval(this.updateTime, 1000);
    this.loadNextAlarm();
    
    // 每分钟重新加载下一个闹钟，确保信息准确
    this.alarmTimer = setInterval(() => {
      this.loadNextAlarm();
    }, 60000);
  },
  onHide() {
    this.clearTimer();
  },
  onUnload() {
    this.clearTimer();
  },
  methods: {
    updateTime() {
      const now = new Date();
      const h = String(now.getHours()).padStart(2, "0");
      const m = String(now.getMinutes()).padStart(2, "0");
      const s = String(now.getSeconds()).padStart(2, "0");
      this.currentTime = `${h}:${m}:${s}`;
      const y = now.getFullYear();
      const mon = String(now.getMonth() + 1).padStart(2, "0");
      const d = String(now.getDate()).padStart(2, "0");
      const w = ["日", "一", "二", "三", "四", "五", "六"][now.getDay()];
      this.currentDate = `${y}-${mon}-${d} 周${w}`;
      
      // 更新倒计时
      this.updateCountdown();
    },
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      if (this.alarmTimer) {
        clearInterval(this.alarmTimer);
        this.alarmTimer = null;
      }
    },
    goToAddAlarm() {
      uni.navigateTo({ url: "/pages/add-alarm/add-alarm" });
    },
    goToRealDeviceTest() {
      uni.navigateTo({ url: "/pages/real-device-test/real-device-test" });
    },
    loadNextAlarm() {
      try {
        let alarms = [];
        const alarmsData = uni.getStorageSync("alarms");
        
        if (alarmsData) {
          if (typeof alarmsData === 'string') {
            alarms = JSON.parse(alarmsData);
          } else if (Array.isArray(alarmsData)) {
            alarms = alarmsData;
          }
        }
        
        const activeAlarms = alarms.filter((alarm) => alarm.isActive);

        if (activeAlarms.length > 0) {
          // 找到最近的闹钟
          const now = new Date();
          const currentTime = now.getHours() * 60 + now.getMinutes();

          let nextAlarm = null;
          let minTimeDiff = Infinity;

          activeAlarms.forEach((alarm) => {
            const [hours, minutes] = alarm.time.split(":").map(Number);
            const alarmTime = hours * 60 + minutes;

            let timeDiff = alarmTime - currentTime;
            if (timeDiff < 0) {
              timeDiff += 24 * 60; // 明天的闹钟
            }

            if (timeDiff < minTimeDiff) {
              minTimeDiff = timeDiff;
              nextAlarm = alarm;
            }
          });

          this.nextAlarm = nextAlarm;
        } else {
          this.nextAlarm = null;
        }
      } catch (error) {
        console.error("加载下一个闹钟失败:", error);
        this.nextAlarm = null;
      }
    },
    
    updateCountdown() {
      if (!this.nextAlarm) {
        this.countdown = "";
        return;
      }
      
      const now = new Date();
      const [hours, minutes] = this.nextAlarm.time.split(":").map(Number);
      
      // 计算下次响铃时间
      let nextRingTime = new Date();
      nextRingTime.setHours(hours, minutes, 0, 0);
      
      // 如果时间已过，设为明天
      if (nextRingTime <= now) {
        nextRingTime.setDate(nextRingTime.getDate() + 1);
      }
      
      // 对于重复闹钟，需要考虑星期设置
      if (this.nextAlarm.type === 'repeat' && this.nextAlarm.repeatDays && this.nextAlarm.repeatDays.length > 0) {
        const currentDay = now.getDay();
        const repeatDays = this.nextAlarm.repeatDays;
        
        // 找到下一个匹配的星期
        let daysToAdd = 0;
        let found = false;
        
        for (let i = 0; i < 7; i++) {
          const checkDay = (currentDay + i) % 7;
          if (repeatDays.includes(checkDay)) {
            if (i === 0 && nextRingTime > now) {
              // 今天且时间未过
              daysToAdd = 0;
            } else if (i > 0) {
              // 未来几天
              daysToAdd = i;
            } else {
              // 今天但时间已过，找下一个匹配日
              continue;
            }
            found = true;
            break;
          }
        }
        
        if (found) {
          nextRingTime = new Date();
          nextRingTime.setHours(hours, minutes, 0, 0);
          nextRingTime.setDate(nextRingTime.getDate() + daysToAdd);
        }
      }
      
      const timeDiff = nextRingTime - now;
      
      if (timeDiff > 0) {
        const totalMinutes = Math.floor(timeDiff / (1000 * 60));
        const days = Math.floor(totalMinutes / (24 * 60));
        const remainingMinutes = totalMinutes % (24 * 60);
        const displayHours = Math.floor(remainingMinutes / 60);
        const displayMinutes = remainingMinutes % 60;
        
        if (days > 0) {
          this.countdown = `${days}天${displayHours}小时${displayMinutes}分钟后响铃`;
        } else if (displayHours > 0) {
          this.countdown = `${displayHours}小时${displayMinutes}分钟后响铃`;
        } else {
          this.countdown = `${displayMinutes}分钟后响铃`;
        }
      } else {
        this.countdown = "即将响铃";
      }
    },
    
    getAlarmTypeText(alarm) {
      if (alarm.type === 'once') {
        return `一次性闹钟 - ${this.formatDate(alarm.date)}`;
      } else if (alarm.type === 'repeat') {
        const weekDays = ["日", "一", "二", "三", "四", "五", "六"];
        const repeatDaysText = alarm.repeatDays.map(day => weekDays[day]).join('、');
        return `重复闹钟 - 每周${repeatDaysText}`;
      } else {
        return "闹钟";
      }
    },
    
    formatDate(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}/${month}/${day}`;
    },
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  padding: 40rpx 30rpx;
  background-color: #f6f8fb;
  box-sizing: border-box;
}
.clock-container {
  margin-top: 80rpx;
  text-align: center;
}
.time-display .time {
  font-size: 120rpx;
  font-weight: 700;
  letter-spacing: 4rpx;
  color: #222;
}
.date-display .date {
  margin-top: 20rpx;
  font-size: 32rpx;
  color: #666;
}
.button-container {
  margin-top: 60rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
}
.add-alarm-btn {
  background-color: #007aff;
  color: #fff;
  border-radius: 50rpx;
  padding: 20rpx 40rpx;
  font-size: 32rpx;
  width: 300rpx;
}
.test-btn {
  background-color: #ff6b35;
  color: #fff;
  border-radius: 50rpx;
  padding: 15rpx 30rpx;
  font-size: 28rpx;
  width: 300rpx;
}
.next-alarm-container {
  margin-top: 40rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.next-alarm-header {
  text-align: center;
  margin-bottom: 20rpx;
}

.next-alarm-label {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.next-alarm-info {
  text-align: center;
  margin-bottom: 15rpx;
}

.next-alarm-time {
  display: block;
  font-size: 48rpx;
  font-weight: 700;
  color: #007aff;
  margin-bottom: 10rpx;
}

.next-alarm-name {
  display: block;
  font-size: 32rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.alarm-features-preview {
  display: flex;
  justify-content: center;
  gap: 15rpx;
}

.feature-preview {
  font-size: 24rpx;
  padding: 5rpx 10rpx;
  background-color: #f0f0f0;
  border-radius: 10rpx;
}

.countdown {
  text-align: center;
  margin-bottom: 15rpx;
}

.countdown-text {
  font-size: 26rpx;
  color: #ff6b35;
  font-weight: 500;
}

.next-alarm-type {
  text-align: center;
}

.type-text {
  font-size: 24rpx;
  color: #999;
}

.no-alarm {
  margin-top: 40rpx;
  text-align: center;
  padding: 60rpx 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
}

.no-alarm-text {
  font-size: 28rpx;
  color: #999;
}
</style>
